import click
import json
import os
from extensions import db
from models import User, Category, Website

@click.command('init-db')
@click.option('--file', default='init_data.json', help='初始化数据文件路径')
def init_db(file):
    """初始化数据库并从 JSON 文件导入数据"""
    from app import create_app
    app = create_app()
    with app.app_context():
        db.create_all()
        # 找同文件夹下的文件
        file = os.path.join(os.path.dirname(__file__), file)
        if not os.path.exists(file):
            print(f"❌ 文件未找到: {file}")
            return

        with open(file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        print("✅ 开始导入数据...")
        # 用户
        print("✅ 开始导入用户...")
        for item in data.get('users', []):
            if not User.query.filter_by(username=item['username']).first():
                user = User(
                    username=item['username'],
                    email=item['email'],
                    role=item['role'],
                    is_deleted=item['is_deleted'],
                    is_system=True
                )
                user.set_password(item['password'])
                db.session.add(user)
            print( f"✅ 添加用户: {item['username']}")
        print( "✅ 添加用户完成")
        # 分类
        print("✅ 开始添加分类...")
        for item in data.get('categories', []):
            category = Category.query.filter_by(name=item['name']).first()
            if not category:
                cat = Category()
                cat.id = int(item['id'])
                cat.name = item['name']
                cat.description = item['description']

                db.session.add(cat)
                db.session.flush()  # 获取 ID 不提交事务
                print( f"✅ 添加分类: {item['name']}")
        print( "✅ 添加分类完成")

        # 网站
        print("✅ 开始添加网站...")
        for item in data.get('websites', []):
            if not Website.query.filter_by(url=item['url']).first():
                website = Website(
                    name=item['name'],
                    url=item['url'],
                    logo=item['logo'],
                    description=item['description'],
                    category_id=int(item['category_id']),
                    status='active',
                    is_system=True
                )
                db.session.add(website)
                print( f"✅ 添加网站: {item['name']}")
        print( "✅ 添加网站完成")
        db.session.commit()
        print("✅ 数据库初始化完成")
